package com.controller.common;

import com.entity.common.ApiResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 登录模块
 */
@Controller
public class LoginController {

    private static final transient Logger log = LoggerFactory.getLogger(LoginController.class);

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/doLogin",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult login(@RequestParam("username") String username,
                           @RequestParam("password") String password){
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            // 把用户名和密码封装为 UsernamePasswordToken 对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                // 执行登录.
                currentUser.login(token);
               return new ApiResult(true,"登录成功！");
            }
            // 没有指定的账户
            catch (UnknownAccountException uae) {
                return new ApiResult(false,"用户名不存在！");
            }
            // 账户存在, 但密码不匹配
            catch (IncorrectCredentialsException ice) {
                return  new ApiResult(false,"密码错误！");
            }
            // 用户被锁定
            catch (LockedAccountException loe){
                return new ApiResult(false,"用户已被锁定！");
            }
            // 所有认证时异常的父类.
            catch (AuthenticationException ae) {
                return new ApiResult(false,"登录发生异常！");
            }
        }
        else{
            return new ApiResult(true,"登录成功！");
        }
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/";
    }

    //首页地址
    @RequestMapping("/")
    public String index(Model model, HttpServletResponse response) {
        return "index";
    }

    @RequestMapping("/checkIsLogin")
    @ResponseBody
    public boolean checkIsLogin() {
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()){
            return  true;
        }
        return  false;
    }
}
